import React, { createRef } from 'react'

class MulFlavorForm extends React.Component {
  constructor(props) {
    super(props)

    // createRef创建引用
    this.select = createRef()

    this.state = {
      value: "coconut",
      arr: [],
      options: [
        { value: "grapefruit", label: "葡萄柚" },
        { value: "lime", label: "酸橙" },
        { value: "coconut", label: "椰子" },
        { value: "mango", label: "芒果" }
      ]
    };
  }

  handleSelect = (e) => {
    let select = this.select.current
    // select.options.map()
    let arr = []
    Array.from(select.options).forEach(option => {
      if (option.selected) {
        arr.push(option.value)
      }
    })
    this.setState({
      arr
    })
  }

  render() {
    return (
      <div>
        <select 
          ref={this.select}
          multiple={true} 
          defaultValue={this.state.arr}
          onMouseUp={this.handleSelect}
          // onTouchStart={this.handleSelect}
        >
          {this.state.options.map((item,index) => {
            return <option value={item.value} key={index}>{item.label}</option>;
          })}
        </select>
        {this.state.arr}
      </div>
    );
  }
}

export default MulFlavorForm

